﻿using NewsPortal.Web.Infrastructure.IOC;
using StructureMap;
using StructureMap.Configuration.DSL;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;
using System;
using System.Linq;

namespace NewsPortal.Web.Infrastructure.AppEvents.Application_Start
{
    public class SetUpIOCContainer: IAppEventHandler
    {
        public AppEventType EventType
        {
            get { return AppEventType.Application_Start;  }
        }

        public void Execute()
        {
            DependencyResolver.SetResolver(new StructureMapDependencyResolver());
                
            ObjectFactory.Configure(config =>
            {
                config.Scan(scan =>
                {
                    scan.Assembly(Assembly.GetExecutingAssembly());
                    scan.WithDefaultConventions();
                });

                this.GetAllRegistries().ForEach(reg => config.AddRegistry(reg));
            });
        }

        private IEnumerable<Registry> GetAllRegistries()
        {
            Type baseType = typeof(Registry);
            List<Registry> result = new List<Registry>();

            Assembly.GetExecutingAssembly().GetTypes().Where(t => baseType.IsAssignableFrom(t))
                .ForEach(t => result.Add((Registry)Activator.CreateInstance(t)));

            return result;
        }
    }
}